package com.taotao.search.service.impl;

import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.taotao.common.pojo.SearchItem;
import com.taotao.common.pojo.SearchResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.search.dao.SearchItemDao;
import com.taotao.search.mapper.SearchItemMapper;
import com.taotao.search.service.SearchItemService;
/*
 * 同步数据库数据到索引库
 */
@Service
@Transactional
public class SearchItemServiceImpl implements SearchItemService{

	@Autowired
	private SearchItemMapper searchItemMapper;
	
	@Autowired
	private SolrServer solrServer;
	
	@Autowired
	private SearchItemDao searchItemDao;
	@Override
	public TaotaoResult SynDataToIndexSearchService() throws Exception {
		List<SearchItem> list = searchItemMapper.getItemList();
		for (SearchItem searchItem : list) {
			SolrInputDocument document = new SolrInputDocument();
			
			document.addField("id", searchItem.getId());
			document.addField("item_title", searchItem.getTitle());
			document.addField("item_sell_point", searchItem.getSell_point());
			document.addField("item_price", searchItem.getPrice());
			document.addField("item_image", searchItem.getImage());
			document.addField("item_category_name", searchItem.getCategory_name());
			document.addField("item_desc", searchItem.getItem_des());
			
			solrServer.add(document);
		}
		
		solrServer.commit();
		return TaotaoResult.ok();
	}
	@Override
	public SearchResult getSearchResult(String queryStr, Integer page, Integer rows) throws Exception {
		// 1、创建一个SolrQuery对象。
				SolrQuery query = new SolrQuery();
				// 2、设置查询条件
				query.setQuery(queryStr);
				// 3、设置分页条件
				query.setStart((page - 1) * rows);
				query.setRows(rows);
				// 4、需要指定默认搜索域。
				query.set("df", "item_title");
				// 5、设置高亮
				query.setHighlight(true);
				query.addHighlightField("item_title");
				query.setHighlightSimplePre("<em style=\"color:red\">");
				query.setHighlightSimplePost("</em>");
				// 6、执行查询，调用SearchDao。得到SearchResult
				SearchResult result = searchItemDao.indexSearch(query);
				// 7、需要计算总页数。
				long recordCount = result.getRecordCount();
				long pageCount = recordCount / rows;
				if (recordCount % rows > 0) {
					pageCount++;
				}
				result.setPageCount(pageCount);
				// 8、返回SearchResult
				return result;

	}

}
